package com.foodorder.repository;

import com.foodorder.entity.Refund;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 退款数据访问层
 */
@Repository
public interface RefundRepository extends JpaRepository<Refund, Long> {
    
    /**
     * 根据用户ID查找退款申请（按创建时间倒序）
     */
    List<Refund> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    /**
     * 根据店铺ID查找退款申请（按创建时间倒序）
     */
    List<Refund> findByStoreIdOrderByCreatedAtDesc(Long storeId);
    
    /**
     * 根据状态查找退款申请（按创建时间升序）
     */
    List<Refund> findByStatusOrderByCreatedAtAsc(Refund.RefundStatus status);
    
    /**
     * 查找订单的活跃退款申请（未完成/未拒绝/未取消）
     */
    @Query("SELECT r FROM Refund r WHERE r.orderId = :orderId AND r.status IN ('PENDING', 'PROCESSING')")
    List<Refund> findActiveRefundsByOrderId(@Param("orderId") Long orderId);
    
    /**
     * 根据订单ID查找所有退款申请
     */
    List<Refund> findByOrderIdOrderByCreatedAtDesc(Long orderId);
    
    /**
     * 统计店铺退款数量
     */
    long countByStoreId(Long storeId);
    
    /**
     * 统计指定状态的退款数量
     */
    long countByStatus(Refund.RefundStatus status);
    
    /**
     * 统计店铺指定状态的退款数量
     */
    long countByStoreIdAndStatus(Long storeId, Refund.RefundStatus status);
    
    /**
     * 计算店铺总退款金额
     */
    @Query("SELECT SUM(r.refundAmount) FROM Refund r WHERE r.storeId = :storeId AND r.status = com.foodorder.entity.Refund$RefundStatus.COMPLETED")
    BigDecimal sumRefundAmountByStoreId(@Param("storeId") Long storeId);
    
    /**
     * 计算总退款金额
     */
    @Query("SELECT SUM(r.refundAmount) FROM Refund r WHERE r.status = com.foodorder.entity.Refund$RefundStatus.COMPLETED")
    BigDecimal sumTotalRefundAmount();
    
    /**
     * 查找指定时间范围内的退款申请
     */
    @Query("SELECT r FROM Refund r WHERE r.createdAt BETWEEN :startTime AND :endTime ORDER BY r.createdAt DESC")
    List<Refund> findRefundsBetweenDates(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
    
    /**
     * 查找超时未处理的退款申请
     */
    @Query("SELECT r FROM Refund r WHERE r.status = com.foodorder.entity.Refund$RefundStatus.PENDING AND r.createdAt <= :timeThreshold")
    List<Refund> findTimeoutPendingRefunds(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 查找处理中但长时间未完成的退款
     */
    @Query("SELECT r FROM Refund r WHERE r.status = com.foodorder.entity.Refund$RefundStatus.PROCESSING AND r.reviewedAt <= :timeThreshold")
    List<Refund> findStuckProcessingRefunds(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 根据退款类型统计
     */
    @Query("SELECT r.refundType, COUNT(r) FROM Refund r GROUP BY r.refundType")
    List<Object[]> countRefundsByType();
    
    /**
     * 按月统计退款数量
     */
    @Query("SELECT COUNT(r) FROM Refund r WHERE YEAR(r.createdAt) = :year AND MONTH(r.createdAt) = :month")
    long countRefundsByMonth(@Param("year") int year, @Param("month") int month);
    
    /**
     * 按月统计退款金额
     */
    @Query("SELECT SUM(r.refundAmount) FROM Refund r WHERE r.status = com.foodorder.entity.Refund$RefundStatus.COMPLETED AND YEAR(r.createdAt) = :year AND MONTH(r.createdAt) = :month")
    BigDecimal sumRefundAmountByMonth(@Param("year") int year, @Param("month") int month);
    
    /**
     * 查找高金额退款申请
     */
    @Query("SELECT r FROM Refund r WHERE r.refundAmount >= :amountThreshold ORDER BY r.refundAmount DESC")
    List<Refund> findHighAmountRefunds(@Param("amountThreshold") BigDecimal amountThreshold);
    
    /**
     * 查找用户最近的退款申请
     */
    @Query("SELECT r FROM Refund r WHERE r.userId = :userId ORDER BY r.createdAt DESC LIMIT 1")
    Refund findLatestRefundByUserId(@Param("userId") Long userId);
}